<?php

namespace app\admin\controller;

use my\Define;

use think\Cache;
use think\Db;
use think\Session;
use think\Verify;



class Admin extends Base
{

    /**
     * 管理员列表 */
    public function index()
    {
        $roles = Db::name('admin_role')->column('role_id,role_name');
        $this->assign('url', url('table'));
        $this->assign('roles', $roles);
        $this->assign('self', session('admin_id'));
        if (IS_POST) {
            return json(array('status' => 1, 'html' => $this->fetch('table')));
        }
        return $this->fetch();
    }

    public function table()
    {
        $page = input('get.page');
        $limit = input('get.limit');
        $map = array();
        $base_condition = $this->base_condition;
        if ($base_condition['admin_id'])
            $map['admin_id'] = $base_condition['admin_id'];
        $info = DB::name('admin')->where($map)->page($page, $limit)->select();
        $count = DB::name('admin')->where($map)->count();
        $role = db('admin_role');
        foreach ($info as $key => $val) {
            $info[$key]['role'] = $role->where('role_id', $val['role_id'])->value('role_name');
            $info[$key]['add_time'] = date('Y-m-d H:i:s', $val['add_time']);
            $info[$key]['their_name']='';
            if($val['is_css']==1){
                $their = DB::name('their')->where("admin_id=".$val['admin_id'])->find();
                $info[$key]['their_name']=$their['their_name'];
            }
        }
        echo json_encode(array(
            'code' => 0,
            'msg' => '',
            'count' => $count,
            'data' => $info
        ));
    }

    public function search()
    {
        $page = input('get.page');
        $limit = input('get.limit');
        $map = array();
        $base_condition = $this->base_condition;
        if ($base_condition['admin_id'])
            $map['admin_id'] = $base_condition['admin_id'];
        $start = strtotime(input('get.start'));
        $end = strtotime(input('get.end'));
        $role = input('get.role');
        input('get.start') && $map['add_time'] = array('egt', $start);
        input('get.end') && $map['add_time'] = array('elt', $end);
        input('get.start') && input('get.end') && $map['add_time'] = array('between', array($start, $end));
        $role && $map['role_id'] = $role;
        //管理员名称搜索
        $admin_name = input('get.admin_name');
        if (!empty($admin_name)) {
            $map['user_name'] = ['like', '%' . rtrim($admin_name) . '%'];
        }
        $info = DB::name('admin')->where($map)->page($page, $limit)->select();
        $count = DB::name('admin')->where($map)->count();
        $role = db('admin_role');
        foreach ($info as $key => $val) {
            $info[$key]['role'] = $role->where('role_id', $val['role_id'])->value('role_name');
            $info[$key]['add_time'] = date('Y-m-d H:i:s', $val['add_time']);
        }
        echo json_encode(array(
            'code' => 0,
            'msg' => '',
            'count' => $count,
            'data' => $info
        ));
    }

    /**
     * 修改管理员密码
     * @return \think\mixed|string
     */
    public function modify_pwd()
    {
        $db = db('admin');
        $admin = $db->where('admin_id', session('admin_id'))->find();
        $oldPwd = input('post.old_pw');
        $newPwd = input('post.new_pw');
        $new2Pwd = input('post.new_pw2');
        if (IS_POST) {
            //修改密码
            $enOldPwd = md5($oldPwd);
            $enNewPwd = md5($newPwd);
            if (input('post.admin_id') != session('admin_id')) {
                $this->error('非法操作', '', '', 1);
            } else if ($admin['password'] != $enOldPwd) {
                $this->error('旧密码不正确', '', '', 1);
            } else if ($newPwd != $new2Pwd) {
                $this->error('两次密码不一致', '', '', 1);
            } else {
                $data['admin_id'] = $admin['admin_id'];
                $data['password'] = $enNewPwd;
                $admin['is_init'] == 1 && $data['is_init'] = 2;
                $row = $db->update($data);
                $tip = "修改失败";
                if ($row) {
                    $tip = "修改成功";
                    if ($admin['is_init'] == 1) {
                        $this->redirect(url('index/index'));
                    }
                }
                return "<script>alert('$tip');</script>";
            }
        }
        $config['admin_id'] = session('admin_id');
        $config['init'] = $admin['is_init'];
        $this->assign($config);
        return view();
    }

    /**
     * 添加、编辑管理员页面
     */
    public function admin_info()
    {
        $admin_id = input('get.admin_id/d', 0);
        $base_condition = $this->base_condition;

        $config['act'] = empty($admin_id) ? 'add' : 'edit'; //添加或编辑
        $config['super'] = $base_condition['admin_type'] > 1 ? false : true;
        $config['type'] = $base_condition['admin_type'];
        $region = db('region');
        (empty($config['type']) || $config['type'] == 2) && $where['parent_id'] = 1;
        $where['region_id'] = $base_condition ? array('in', $base_condition['region'][2]) : array('notin', array(33, 34, 35));
        $info['is_css']=2;
        $config['info'] =$info;
        if ($admin_id) {
            $info = Db::name('admin')->where("admin_id", $admin_id)->find();
            $info['region'] = json_decode($info['region'], true);
            $info['franchiseeArr'] = !empty($info['franchisee_str']) ? explode(',', $info['franchisee_str']) : [];
            $info['password'] = "";
            if($info['is_css']==1){
                $their = DB::name('their')->where("admin_id=".$info['admin_id'])->find();
                $info['their_name']=$their['their_name'];
            }
            $config['info'] = $info;
            $config['pro_all'] = true;
            $count_p = $region->where($where)->count();

            if ($count_p != count($info['region'][2])) {
                $config['pro_all'] = false;
            }
            /* 超管及省管 */
            if (empty($config['type']) || $config['type'] == 2) {
                /* 管理省 */
                $config['edit_provinces'] = $region->where('region_id', 'in', $info['region'][2])->column('region_id,region_name');
                foreach ($info['region'][2] as $vp) {
                    $config['edit_citys'][$vp] = $region->where('parent_id', $vp)->column('region_id,region_name');
                }
                /* 管理市 */
                $map['region_name'] = array(array('eq', "市辖区"), array('like', "%县%"), array('like', "%市"), array('like', "%旗%"), 'or');
                foreach ($info['region'][3] as $key_ps => $val_ps) {
                    $config['edit_city_ps'][$key_ps] = $region->where('region_id', 'in', $val_ps)->column('region_id,region_name');
                    foreach ($val_ps as $v) {
                        $map['parent_id'] = $v;
                        $config['edit_countys'][$key_ps][$v] = $region->where($map)->column('region_id,region_name');
                    }
                    $config['city_all'][$key_ps] = true;
                    $count_ct = $region->where('parent_id', $key_ps)->count(); //被编辑人员对应省所管理的市级数
                    if ($count_ct != count($val_ps)) {
                        $config['city_all'][$key_ps] = false;
                    }
                }
                /* 管理县区 */
                foreach ($info['region'][4] as $key_cs => $val_cs) {
                    $config['county_all'][$key_cs] = true;
                    $count_co = $region->where('parent_id', $key_cs)->count();
                    if ($count_co != count($val_cs)) {
                        $config['county_all'][$key_cs] = false;
                    }
                }
            } /* 市管及区县管理 ---和超管及省管的区域思路对换即可 */ else {
                /* 管理省 */
                $config['edit_provinces'] = $region->where('region_id', 'in', $info['region'][2])->column('region_id,region_name');
                foreach ($base_condition['region'][3] as $key => $val) {
                    $config['edit_citys'][$key] = $region->where('region_id', 'in', $val)->column('region_id,region_name');
                }
                /* 管理市 */
                $map['region_name'] = array(array('eq', "市辖区"), array('like', "%县%"), array('like', "%市"), array('like', "%旗%"), 'or');
                foreach ($base_condition['region'][3] as $key_ps => $val_ps) {
                    $config['edit_city_ps'][$key_ps] = $region->where('region_id', 'in', $val_ps)->column('region_id,region_name');
                    foreach ($val_ps as $v) {
                        if ($base_condition['admin_type'] == 3) {
                            $map['parent_id'] = array('in', $val_ps);
                        } else {
                            $map['region_id'] = array('in', $base_condition['region'][4][$v]);
                        }
                        $config['edit_countys'][$key_ps][$v] = $region->where($map)->column('region_id,region_name');
                    }
                    $config['city_all'][$key_ps] = true;
                    $count_ct = count($info['region'][3][$key_ps]); //被编辑人员对应省所管理的市级数
                    if ($count_ct != count($val_ps)) {
                        $config['city_all'][$key_ps] = false;
                    }
                }
                /* 管理县区 */
                foreach ($base_condition['region'][4] as $key_cs => $val_cs) {
                    $config['county_all'][$key_cs] = true;
                    $count_co = count($info['region'][4][$key_ps]); //被编辑人员对应市所管理的区县级数
                    if ($count_co != count($val_cs)) {
                        $config['county_all'][$key_cs] = false;
                    }
                }
            }
        }

        $config['role'] = session('act_list') == 'all' ? Db::name('admin_role')->select() : Db::name('admin_role')->where('role_id', 'neq', 1)->select(); //超管只添加省级总管

        $config['phone_reg'] = Define::RULE_MOBILE;

        $css = Db::name('admin_role')->where('role_name', 'like', '%客服%')->column('role_id') ?: array();
        $config['css'] = json_encode($css);

        $admin_type = admin_type();
        for ($i = 0; $i < $base_condition['admin_type']; $i++) {
            unset($admin_type[$i]);
        }
        $config['levels'] = $admin_type;
        $config['url'] = url('region');
        $config['provinces'] = $region->where($where)->column('region_id,region_name');
        //查询加盟商信息数据
        //$franchisee_info = Db::connect('db2')->table('franchisee')->field('id,name')->where('is_delete', 0)->select();
        //$config['franchiseeList'] = $franchisee_info;

        $this->assign($config);
        return view();
    }

    //添加、编辑管理员时----获取管理区域
    public function region()
    {
        $data_post = input('post.');
        if (!in_array($data_post['level'], array(2, 3))) {
            return json(array('status' => 0, 'msg' => '管理级别参数错误'));
        }
        $base_condition = $this->base_condition;
        $config['admin_type'] = $data_post['level'] + 1;
        switch ($data_post['level']) {
            case 2:
                if ($base_condition['admin_type'] >= 3) {
                    $tmp = array();
                    foreach ($base_condition['region'][3] as $value) {
                        $tmp = array_merge($tmp, $value);
                    }
                    $map['c.region_id'] = array('in', $tmp);
                }
                $config['level'] = 'city';
                break;
            case 3:
                $base_condition['admin_type'] == 4 && $map['c.region_id'] = $base_condition['region_area'];
                $config['level'] = 'county';
                $config['pro'] = 'city';
                //******让市辖区显示出来,否则订单的start_code找不到  2018-10-25
                // $map['c.region_name'] = array(array('eq',"市辖区"),array('like',"%县%"),array('like',"%市"),array('like',"%旗%"),'or');
                break;
        }
        $db = db('region');
        $map['c.parent_id'] = array('in', $data_post['pid']);
        $region = $db->alias('c')->join('region p', 'c.parent_id=p.region_id')
            ->where($map)->column('c.region_id,c.parent_id,c.region_name as child,p.region_name as parent');
        if (empty($region)) {
            return json(array('status' => 2, 'msg' => '没有相关子级区域'));
        }
        foreach ($region as $key => $val) {
            $pid = $val['parent_id'];
            unset($val['parent_id']);
            if ($data_post['level'] == 3) {
                $config['grand'][$pid] = $db->alias('c')->join('region p', 'c.parent_id=p.region_id')
                    ->where('c.region_id', 'in', $pid)->value('p.region_id');
            }
            $config['parents'][$pid] = $val['parent'];
            unset($val['parent']);
            $config['children'][$pid][] = $val;
        }
        $this->assign($config);
        return json(array('status' => 1, 'html' => $this->fetch()));
    }

    /**
     * 添加、编辑管理员
     */
    public function adminHandle()
    {
        $data_post = input('post.');

        $data['user_phone'] = $data_post['user_phone'];
        $data['role_id'] = $data_post['role_id'];
        $data['admin_type'] = $data_post['admin_type'];
        $data['user_name'] = $data_post['user_name'];
        $data['is_css'] = $data_post['is_css'];
        $data['their_name'] = $data_post['their_name'];
        if ($data_post['admin_type'] > 1) {
            $data['region'] = json_encode($data_post['region']);
            switch ($data_post['admin_type']) {
                case 2:
                    $data['region_area'] = implode(',', $data_post['region'][2]);
                    break;
                case 3:
                    $tmp = array();
                    foreach ($data_post['region'][2] as $val) {
                        $tmp = array_merge($tmp, $data_post['region'][3][$val]);
                    }
                    $data['region_area'] = implode(',', $tmp);
                    break;
                case 4:
                    $tmp = array();
                    foreach ($data_post['region'][3] as $key => $val) {
                        foreach ($val as $v) {
                            $tmp = array_merge($tmp, $data_post['region'][4][$v]);
                        }
                    }
                    $data['region_area'] = implode(',', $tmp);
                    break;
                case 5:
                    $data['franchisee_str'] = implode(',', $data_post['franchisee']);
                    break;
            }
        }
        //$data['is_css'] = 2;
        $css = Db::name('admin_role')->where('role_name', 'like', '%客服%')->column('role_id') ?: array();
        if (in_array($data_post['role_id'], $css)) {
            $data['is_css'] = 1;
        }
        switch ($data_post['act']) {
            case 'add':
                $data['password'] = empty($data_post['password']) ? md5('123456') : md5($data_post['password']); //密码默认为123456
                $data['add_time'] = time();
                if (Db::name('admin')->where("user_name", $data_post['user_name'])->count()) {
                    $this->error("此用户名已被注册，请更换", U('Admin/Admin/admin_info'));
                }
                $admin_id = $r = Db::name('admin')->insertGetId($data);
                $this->cacheAdminArea($admin_id);
                break;
            case 'edit':
                $data['admin_id'] = $admin_id = $data_post['admin_id'];
                $data_post['password'] && $data['password'] = md5($data_post['password']);
                $r = Db::name('admin')->update($data);
                $this->clear_admin_cache($admin_id);
                break;
            default:
                return "<script type='application/javascript'>alert('参数异常');parent.window.location.reload();</script>";
                break;
        }
        if ($r) {
            $this->dealAdminArea($data_post['region'][$data_post['admin_type']], $admin_id, $data_post['admin_type'], $data_post['act']);
            if($data_post['is_css']==1){
                $driverData['admin_id'] = $r;
                $driverData['their_name'] =$data_post['their_name'];
                $their=Db::name('their')->insertGetId($driverData);
            }
            return "<script type='application/javascript'>alert('操作成功');parent.window.location.reload();</script>";
        } else {
            $tip = "操作失败";
            if ($r === 0 && $data_post['act'] == 'edit') {
                $tip = "您未作任何改变";
            }
            return "<script type='application/javascript'>alert('$tip');parent.window.location.reload();</script>";
        }
    }

    /**
     * 处理管理员管理区域的数据
     * @param $region_arr
     * @param $admin_id
     * @param $level
     * @param $act
     * */
    private function dealAdminArea($region_arr, $admin_id, $level, $act = 'add')
    {
        $admin_area = db('admin_area');
        $act == 'edit' && $admin_area->where('admin_id', $admin_id)->delete();
        switch ($level) {
            case 2:
                foreach ($region_arr as $key => $val) {
                    $data[$key]['region_area'] = $val;
                    $data[$key]['admin_id'] = $admin_id;
                }
                $admin_area->insertAll($data);
                break;
            default:
                foreach ($region_arr as $key => $value) {
                    foreach ($value as $k => $val) {
                        $data[$k]['region_area'] = $val;
                        $data[$k]['admin_id'] = $admin_id;
                    }
                    $admin_area->insertAll($data);
                }
                break;
        }
    }

    public function adminArea()
    {
        $admin_id = input('get.admin_id/d', 0);
        $admin_area = Cache::get("area_$admin_id");
        if (empty($admin_area)) {
            $admin_area = $this->cacheAdminArea($admin_id);
        }
        $page = input('get.page/d', 0);
        $limit = input('get.limit/d', 0);
        if ($admin_id) {
            $admin_name = Db::name('admin')->where("admin_id", $admin_id)->value('user_name');
            if ($page && $limit) {
                $data = array();
                $offset = ($page - 1) * $limit;
                for ($i = 0; $i < $limit; $i++) {
                    $admin_area[$i + $offset] && $data[$i] = $admin_area[$i + $offset];
                }
                $count = count($admin_area);
                echo json_encode(array(
                    'code' => 0,
                    'msg' => '',
                    'count' => $count,
                    'data' => $data
                ));
                exit;
            }
            $this->assign('url', url('adminArea', array('admin_id' => $admin_id, 'show' => input('get.show'))));
            $this->assign('show', input('get.show'));
            $this->assign('tip', "管理员<span style='color: orangered'>{$admin_name}</span>的管理区域");
            $config['status'] = 1;
            $config['html'] = $this->fetch();
            return json($config);
        }
    }

    /**
     * 删除管理员
     */
    public function adminDel()
    {
        $data = input('post.');
        $return['status'] = 0;
        if ($data['act'] != 'del' || $data['admin_id'] <= 1) {
            $return['msg'] = '参数错误';
            return json($return);
        }
        $r = Db::name('admin')->where('admin_id', $data['admin_id'])->delete();
        $return['msg'] = '请勿重复操作';
        if ($r) {
            $return['msg'] = '';
            $return['status'] = 1;
        }
        return json($return);
    }

    /**
     * 管理员登陆
     */
    public function jy(){
        require_once VENDOR_PATH . 'jysdk/gt3/lib/class.geetestlib.php';
        require_once VENDOR_PATH . 'jysdk/gt3/config/config.php';
        //极验
        $GtSdk = new \GeetestLib('d1650d1308db7f17bf140a6610058df9', '8b53c8c80568b41e56df69f3c31163a9');
        session_start();

        $data = array(
            "user_id" => "admin@xiaomachuxing.com
", # 网站用户id
            "client_type" => "web", #web:电脑上的浏览器；h5:手机上的浏览器，包括移动应用内完全内置的web_view；native：通过原生SDK植入APP应用的方式
            "ip_address" => "127.0.0.1" # 请在此处传输用户请求验证时所携带的IP
        );

        $status = $GtSdk->pre_process($data, 1);
        $_SESSION['gtserver'] = $status;
        $_SESSION['user_id'] = $data['user_id'];
        echo $GtSdk->get_response_str();
    }
    //极验验证
    public function vjy(){
        error_reporting(0);
        require_once VENDOR_PATH  . 'jysdk/gt3/lib/class.geetestlib.php';
        require_once VENDOR_PATH  . 'jysdk/gt3/config/config.php';
        session_start();
        $GtSdk = new \GeetestLib(CAPTCHA_ID, PRIVATE_KEY);

        $data = array(
            "user_id" => $_SESSION['user_id'], # 网站用户id
            "client_type" => "web", #web:电脑上的浏览器；h5:手机上的浏览器，包括移动应用内完全内置的web_view；native：通过原生SDK植入APP应用的方式
            "ip_address" => "127.0.0.1" # 请在此处传输用户请求验证时所携带的IP
        );
        if ($_SESSION['gtserver'] == 1) {   //服务器正常
            $result = $GtSdk->success_validate($_POST['geetest_challenge'], $_POST['geetest_validate'], $_POST['geetest_seccode'], $data);
            if ($result) {
                return 'success';
            } else{
                return 'fail';
            }
        }else{  //服务器宕机,走failback模式
            if ($GtSdk->fail_validate($_POST['geetest_challenge'],$_POST['geetest_validate'],$_POST['geetest_seccode'])) {
                return 'success';
            }else{
                return 'fail';
            }
        }
    }
    public function login()
    {
        if (session('admin_id') && session('admin_id') > 0) {
            $this->success("您已登录", url('Admin/Index/index'));
        }
        if ($_POST) {
            $msg=$this->vjy();
            if ($msg=='fail'){
                exit(json_encode(array('status' => 0, 'msg' => '请先通过验证')));
            }
            $condition['user_name'] = I('post.username/s');
            $condition['password'] = I('post.password/s');
            if (!empty($condition['user_name']) && !empty($condition['password'])) {

                //判断 是否超次数
                $today = strtotime("today");
                $yesterday = strtotime("yesterday");
                $login_true = Db::name('admin_login_log')->where('user_name', $condition['user_name'])
                    ->where('create_time', '>=', time() - 60 * 60 * 60)
                    ->where('login_true', 0)
                    ->count();
                if ($login_true >= 5) {
                    exit(json_encode(array('status' => 0, 'msg' => '密码错误已经超过5次,一小时后再试')));
                }


                $admin_info = Db::name('admin')->join('xm_admin_role', 'xm_admin.role_id=xm_admin_role.role_id', 'INNER')->where($condition)->find();
                if (is_array($admin_info)) {
                    session('admin_id', $admin_info['admin_id']);
                    session('admin_name', $admin_info['user_name']);
                    session('act_list', $admin_info['act_list']);
                    $admin_info['admin_type'] && session('admin_type', $admin_info['admin_type']);
                    Db::name('admin')->where("admin_id = " . $admin_info['admin_id'])->update(array('last_login' => time(), 'last_ip' => request()->ip()));
                    session('last_login_time', $admin_info['last_login']);
                    session('last_login_ip', $admin_info['last_ip']);
                    session('franchisee_str', $admin_info['franchisee_str']);
                    $url = $admin_info['is_init'] == 1 ? url('modify_pwd') : (session('from_url') ? session('from_url') : url('Admin/Index/index'));
                    $this->adminLog(CONTROLLER_NAME . '@' . ACTION_NAME, $_POST, "后台登录");
                    $msg['to'] = $admin_info['admin_id'];
                    $msg['type'] = 'login';
                    $msg['content'] = json_encode(array('act' => 'login', 'remark' => "{$admin_info['user_name']}上线了"));

                    //登录成功记录
                    Db::name('admin_login_log')->insert([
                        'user_name'=> $condition['user_name'],
                        'login_true' => 1,
                        'create_time' => time()
                    ]);

                    exit(json_encode(array('status' => 1, 'url' => $url, 'data' => $_SESSION)));
                } else {
                    //登录失败日志记录
                    Db::name('admin_login_log')->insert([
                        'user_name'=> $condition['user_name'],
                        'login_true' => 0,
                        'create_time' => time()
                    ]);
                    if ($login_true >= 2) {
                        exit(json_encode(array('status' => 0, 'msg' => '账号密码不正确,已尝试' . $login_true."次, 最多尝试5次")));
                    }

                    exit(json_encode(array('status' => 0, 'msg' => '账号密码不正确')));
                }
            } else {
                exit(json_encode(array('status' => 0, 'msg' => '请填写账号密码')));
            }
        } else {
            return $this->fetch();
        }
    }

    /**
     * 退出登陆
     */
    public function logout()
    {
        $this->adminLog(CONTROLLER_NAME . '@' . ACTION_NAME, '', "退出登录");
        //$this->clear_admin_cache(session('admin_id'));
        session_unset();
        session_destroy();
        session::clear();
        $this->success("退出成功", U('Admin/Admin/login'));
    }

    /**
     * 验证码获取
     */
    public function vertify()
    {
        $config = array(
            'fontSize' => 30,
            'length' => 4,
            'useCurve' => true,
            'useNoise' => false,
            'reset' => false
        );
        $Verify = new Verify($config);
        $Verify->entry("admin_login");
        exit();
    }

    /**
     * 角色管理
     * @param string
     * @param int
     * @return \think\controller\mixed //成功时返回
     */
    public function role()
    {
        if (input('get.page')) {
            $page = input('get.page');
            $limit = input('get.limit');
            $start = ($page - 1) * $limit;
            $count = Db::name('admin_role')->count();
            $list = Db::name('admin_role')->limit($start, $limit)->order('role_id desc')->select();
            echo json_encode(array(
                'code' => 0,
                'msg' => '',
                'count' => $count,
                'data' => $list
            ));
            exit;
        }

        return $this->fetch();
    }

    public function role_info()
    {
        $role_id = input('get.role_id/d');
        $detail = array();
        if ($role_id) {
            $detail = Db::name('admin_role')->where("role_id", $role_id)->find();
            $detail['act_list'] = explode(',', $detail['act_list']);
            $this->assign('detail', $detail);
        }
        $right = Db::name('system_menu a')->join('admin_auth_group b', 'a.group=b.kname', 'LEFT')->field('a.*')->where('a.is_del', 0)
            ->order('b.sort asc,b.id asc')->select();
        foreach ($right as $val) {
            if (!empty($detail)) {
                $val['enable'] = in_array($val['id'], $detail['act_list']);
            }
            $modules[$val['group']][] = $val;
        }
        //权限组
        $group = getGroup();
        $this->assign('role_id', $role_id);
        $this->assign('group', $group);
        $this->assign('modules', $modules);
        return $this->fetch();
    }

    /**
     * 添加、编辑角色
     */
    public function roleSave()
    {
        $data = input('post.');
        $res = $data['data'];
        $res['act_list'] = is_array($data['right']) ? implode(',', $data['right']) : '';
        if (empty($res['act_list'])) {
            $this->error("请选择权限!");
        }
        if (empty($data['role_id'])) {
            $admin_role = Db::name('admin_role')->where(['role_name' => $res['role_name']])->find();
            if ($admin_role) {
                $this->error("已存在相同的角色名称!");
            } else {
                $r = Db::name('admin_role')->insert($res);
            }
        } else {
            $admin_role = Db::name('admin_role')->where(['role_name' => $res['role_name'], 'role_id' => ['<>', $data['role_id']]])->find();
            if ($admin_role) {
                $this->error("已存在相同的角色名称!");
            } else {
                $r = Db::name('admin_role')->where('role_id', $data['role_id'])->update($res);
            }
        }
        return "<script type='application/javascript'>alert('操作成功');parent.window.location.reload();</script>";
    }

    /**
     * 角色表删除
     * @param string
     * @param int
     * @return string
     */
    public function ajax_roleDel()
    {
        $role_id = input('post.role_id');
        $admin = Db::name('admin')->where('role_id', $role_id)->find();
        if ($admin) {
            return json(array('status' => 0, 'msg' => '请先清空所属该角色的管理员'));
        }
        $res = Db::name('admin_role')->where('role_id', $role_id)->delete();
        if ($res) {
            return json(array('status' => 1, 'msg' => '删除成功'));
        } else {
            return json(array('status' => 0, 'msg' => '请勿重复操作'));
        }
    }

    //个人资料
    public function selfInfo()
    {
        $config['base_info_arr'] = array(
            'user_name' => '用户名',
            'add_time' => '添加时间',
            'last_login' => '本次登录时间',
            'last_ip' => '本次登录ip',
            'role_name' => '角色名',
            'role_desc' => '角色描述',
        );
        $config['base_info'] = db('admin a')->join('admin_role b', 'a.role_id=b.role_id', 'LEFT')
            ->field(implode(',', array_keys($config['base_info_arr'])) . ',admin_type')
            ->where('admin_id', session('admin_id'))->find();
        $config['base_info']['add_time'] = date('Y-m-d H:i:s', $config['base_info']['add_time']);
        $config['base_info']['last_login'] = date('Y-m-d H:i:s', $config['base_info']['last_login']);
        $config['admin_type'] = $config['base_info']['admin_type'];
        $config['base_info']['admin_type'] = admin_type()[$config['admin_type']];
        $config['url_role'] = url('selfRoleTable');
        $config['url_area'] = url('adminArea', array('admin_id' => session('admin_id')));
        $this->assign($config);
        return view();
    }

    //个人角色
    public function selfRoleTable()
    {
        $page = input('get.page');
        $limit = input('get.limit');
        $map = session('act_list') == 'all' ? array() : array('id' => array('in', session('act_list')));
        $res = db('system_menu')->where($map)->field('id,name,group,right')->page($page, $limit)->select();
        $count = db('system_menu')->where($map)->count();
        $group = getGroup();
        foreach ($res as $key => $val) {
            $res[$key]['group'] = $group[$val['group']];
        }
        echo json_encode(array(
            'code' => 0,
            'msg' => '',
            'count' => $count,
            'data' => $res
        ));
    }

}
